<?php
/**
 * Controller helper for setting controller useful properties.
 * 
 * @package disputeo
 * @version 1.0
 * @author jimmy.dixon
 */

class Disputeo_Controller_Helper_Init extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var $obj Zend_Application_Bootstrap_BootstrapAbstract
     */
    protected $_bootstrap = null;
    
    /**
     * @var $obj Zend_Controller_Request_Abstract
     */
    protected $_request = null;
    
    /**
     * @var $obj Zend_Controller_Action
     */
    protected $_controller = null;
    
    /**
     * @var $obj Zend_View_Abstract
     */
    protected $_view = null;

    /**
     * Initialise application resources
     */
    public function init()
    {
        $this->_bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $this->_request = Zend_Controller_Front::getInstance()->getRequest();
        $this->_controller = $this->getActionController();
        $this->_view = $this->_bootstrap->getResource('view');
        parent::init();
    }

    /**
     * Set controller properties
     */
    public function preDispatch()
    {
        $this->_controller->_session = $this->_request->session;
        $this->_controller->_config = $this->_bootstrap->getOptions();
        $this->_controller->_logger = $this->_bootstrap->getResource('log');
        $this->_controller->_mailer = new Disputeo_Mail();
        $this->_loadMessenger();
        $this->_loadJavaScript();
    }

    /**
     * Initialise controller messenger property
     */
    protected function _loadMessenger()
    {
        $this->_controller->_messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        $messages = (array) $this->_controller->_messenger->getMessages();
        foreach ($messages as $message) {
            if (is_string($message)) {
                $this->_controller->_messenger->$message = true;
            }
        }
    }
    
    /**
     * Include JS file for action
     */
    protected function _loadJavaScript()
    {
        $controller = $this->_request->getControllerName();
        $action = $this->_request->getActionName();
        $jsFile = $controller . '-' . $action . '.js';
        $jsPath = APPLICATION_PATH . '/../public/js/';

        if (is_file($jsPath . $jsFile)) {
            $this->_view->headScript()->appendFile('/js/' . $jsFile);
        }
    }

}
